import { useEffect, useRef, useState, useCallback } from "react";
import Hls from 'hls.js';
import './CameraView.css';

const EnhancedCameraView = ({ cameraId }) => {
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const hlsRef = useRef(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [zoomLevel, setZoomLevel] = useState(1);
  const [isFullscreen, setIsFullscreen] = useState(false);

  // 初始化视频流
  useEffect(() => {
    const initPlayer = () => {
      if (Hls.isSupported()) {
        const hls = new Hls({
          maxBufferLength: 30,
          maxMaxBufferLength: 600,
          maxBufferSize: 60 * 1000 * 1000,
          maxBufferHole: 0.5,
        });
        
        hlsRef.current = hls;
        
        // 使用公共HLS测试流
        const testStreamUrl = 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8';
        hls.loadSource(testStreamUrl);
        hls.attachMedia(videoRef.current);
        
        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          setLoading(false);
        });
        
        hls.on(Hls.Events.ERROR, (event, data) => {
          if (data.fatal) {
            setError('视频流加载失败');
            hls.destroy();
          }
        });
      } else if (videoRef.current.canPlayType('application/vnd.apple.mpegurl')) {
        // Safari原生支持HLS
        const testStreamUrl = 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8';
        videoRef.current.src = testStreamUrl;
        videoRef.current.addEventListener('loadedmetadata', () => {
          setLoading(false);
        });
      } else {
        setError('浏览器不支持视频播放');
      }
    };
    
    initPlayer();

    return () => {
      if (hlsRef.current) {
        hlsRef.current.destroy();
      }
    };
  }, [cameraId]);

  // 截屏功能
  const captureScreenshot = useCallback(() => {
    if (!videoRef.current || !canvasRef.current) return;
    
    const video = videoRef.current;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    
    // 设置canvas尺寸
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    // 绘制当前帧
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    
    // 创建下载链接
    const link = document.createElement('a');
    link.download = `screenshot-${new Date().getTime()}.png`;
    link.href = canvas.toDataURL('image/png');
    link.click();
  }, []);

  // 放大功能
  const zoomIn = () => {
    setZoomLevel(prev => Math.min(prev + 0.5, 3));
  };

  // 缩小功能
  const zoomOut = () => {
    setZoomLevel(prev => Math.max(prev - 0.5, 1));
  };

  // 重置缩放
  const resetZoom = () => {
    setZoomLevel(1);
  };

  // 全屏功能
  const toggleFullscreen = () => {
    if (!videoRef.current) return;
    
    if (!isFullscreen) {
      if (videoRef.current.requestFullscreen) {
        videoRef.current.requestFullscreen();
      }
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
    setIsFullscreen(!isFullscreen);
  };

  // 监听全屏变化
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement);
    };

    document.addEventListener('fullscreenchange', handleFullscreenChange);
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, []);

  return (
    <div className="enhanced-camera-container">
      {loading && <div className="camera-loading">正在连接摄像头...</div>}
      {error && <div className="camera-error">错误: {error}</div>}
      
      <div className="video-controls">
        <button onClick={zoomIn} title="放大">🔍+</button>
        <button onClick={zoomOut} title="缩小">🔍-</button>
        <button onClick={resetZoom} title="重置缩放">↺</button>
        <button onClick={captureScreenshot} title="截屏">📷</button>
        <button onClick={toggleFullscreen} title="全屏">
          {isFullscreen ? '↗' : '⛶'}
        </button>
      </div>

      <div className="video-wrapper">
        <video 
          ref={videoRef} 
          autoPlay 
          playsInline
          muted
          style={{ 
            position: 'absolute',
            top: '0',
            left: '0',
            width: '100%',
            height: '100%',
            minWidth: '100%',
            minHeight: '100%',
            objectFit: 'cover',
            display: loading || error ? 'none' : 'block',
            transform: `scale(${zoomLevel})`,
            transformOrigin: 'center center'
          }}
          onError={() => setError("视频流加载失败")}
        />
      </div>

      <canvas ref={canvasRef} style={{ display: 'none' }} />
    </div>
  );
};

export default EnhancedCameraView;